package com.mingtu.guards.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.center.bean.PatrolPeopleBean;
import com.mingtu.common.base.BaseFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SpacesItemDecoration;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.guards.R;
import com.mingtu.guards.activity.RecordTrackListActivity;
import com.mingtu.guards.adapter.RecordTrackAdapter;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;

import static com.mingtu.guards.utils.MyConstant.ItemDecorationSpaces;

public class TrackRecordFragment extends BaseFragment implements LazyFragmentPagerAdapter.Laziable {


    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.empty_layout)
    EmptyDataLayout emptyLayout;
    @BindView(R.id.tv_total_mileage)
    TextView tvTotalMileage;
    @BindView(R.id.tv_total_time)
    TextView tvTotalTime;
    @BindView(R.id.tv_total_count)
    TextView tvTotalCount;

    private int currentPage = 1;
    private boolean isLoadMore = true;
    private String beginTime = null;
    private String endTime = null;
    private List<String> deptIdList = null;
    private LinkedList<PatrolPeopleBean.PageBean.ListBean> DataBean = new LinkedList<>();
    private RecordTrackAdapter recordTrackAdapter;
    private static final String ARG_PARAM1= "param1";
    private static final String ARG_PARAM2= "param2";

    public static TrackRecordFragment getInstance() {
        TrackRecordFragment ef = new TrackRecordFragment();
        return ef;
    }

    public static TrackRecordFragment getInstance(String beginTime, String endTime) {
        TrackRecordFragment ef = new TrackRecordFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_PARAM1, beginTime);
        bundle.putString(ARG_PARAM2, endTime);
        ef.setArguments(bundle);
        return ef;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            beginTime = getArguments().getString(ARG_PARAM1);
            endTime = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_track_record;
    }

    @Override
    protected void initData() {
        getTrackPeopleList(1);
        getTrackCount();
    }

    @Override
    protected void initView(View view) {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        recycler.setLayoutManager(manager1);
        recycler.addItemDecoration(new SpacesItemDecoration(0, 0, ItemDecorationSpaces, ItemDecorationSpaces, ItemDecorationSpaces));

        recordTrackAdapter = new RecordTrackAdapter(DataBean);
        recycler.setAdapter(recordTrackAdapter);
        recordTrackAdapter.setOnItemClickListener(new RecordTrackAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                String name = DataBean.get(position).getName();
                String userId = DataBean.get(position).getUserId();
                Bundle bundle = new Bundle();
                bundle.putString("name", name);
                bundle.putString("userId", userId);
                IntentUtils.getInstance().readyGo(getActivity(), RecordTrackListActivity.class, bundle);
            }
        });
    }

    @Override
    protected void getData() {
        initListener();
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                getTrackPeopleList(1);
                getTrackCount();
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(DataBean, Constant.PAGE_SIZE);
                    getTrackPeopleList(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    public void setBeginTime(String beginTime) {
        this.beginTime = beginTime;
    }

    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    public void setDeptIdList(List<String> deptIdList) {
        this.deptIdList = deptIdList;
    }

    /**
     * 获得巡护人员数据
     */
    public void getTrackPeopleList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("beginTime", beginTime);
        hashMap.put("endTime", endTime);
        hashMap.put("deptIdList", deptIdList);

        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(Constant.getInstance().POST_PATROL_PEOPLE_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                PatrolPeopleBean patrolPeopleBean = new PatrolPeopleBean();
                                patrolPeopleBean = gson.fromJson(result, PatrolPeopleBean.class);

                                List<PatrolPeopleBean.PageBean.ListBean> dataBeans = patrolPeopleBean.getPage().getList();
                                try {
                                    emptyLayout.setIsShowView(false);
                                    recycler.setVisibility(View.VISIBLE);

                                    if (dataBeans != null) {

                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        if (!isLoadMore) {
                                            if (currentPage > 1) {
                                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_no_more_data));
                                            } else {
                                                if (dataBeans.size() == 0) {
                                                    //显示占位图
                                                    emptyLayout.setIsShowView(true);
                                                    recycler.setVisibility(View.GONE);
                                                }

                                            }
                                        }
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            recordTrackAdapter.clearData();
                                        }

                                        DataBean.addAll(dataBeans);
                                        recordTrackAdapter.upData(DataBean);

                                    } else {
                                        if (currentPage == 1) {
                                            //显示占位图
                                            recycler.setVisibility(View.GONE);
                                            emptyLayout.setIsShowView(true);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                e.printStackTrace();
                                isLoadMore = false;
                                //显示占位图
                                recycler.setVisibility(View.GONE);
                                emptyLayout.setIsShowView(true);
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }


                        }
                    }
                });
    }

    /**
     * 获取巡护统计数据
     */
    public void getTrackCount() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("beginTime", beginTime);
        hashMap.put("endTime", endTime);
        hashMap.put("deptIdList", deptIdList);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_EDPT_TASK_COUNT)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                JSONObject jsonObject = JSON.parseObject(result);
                                JSONObject staticsObject = jsonObject.getJSONObject("statics");

                                String duration = staticsObject.getString("totalDuration");
                                String totalMileage = staticsObject.getString("totalMileage");
                                String times = staticsObject.getString("totalCount");

                                if (!StringUtils.isEmpty(duration)) {
                                    long d = 0;
                                    if (duration.indexOf(".") != -1) {
                                        String array[] = duration.split("\\.");
                                        d = Long.parseLong(array[0]);
                                    } else {
                                        d = Long.parseLong(duration);
                                    }
                                    tvTotalTime.setText(MyUtills.formatSeconds2(d));
                                } else {
                                    tvTotalTime.setText("0");
                                }

                                if (!StringUtils.isEmpty(totalMileage)) {
                                    tvTotalMileage.setText(totalMileage + "");
                                } else {
                                    tvTotalMileage.setText("0");
                                }


                                if (!StringUtils.isEmpty(times)) {
                                    tvTotalCount.setText(times + "");
                                } else {
                                    tvTotalCount.setText("0");
                                }


                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }
}